package com.abl.common.web;


import com.abl.common.cache.CacheService;
import com.abl.common.mybatis.model.Dnt;
import com.abl.common.util.JwtKit;
import com.abl.domain.model.AblError;
import com.abl.service.system.SysService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 权限拦截
 *
 * @author 王永吉
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    SysService system;
    @Autowired
    CacheService cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

        System.out.println(response);
        System.out.println(object);
        System.out.println("6666666666666666666666666666666666");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "authorization,Authorization,Token,Auth,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");

        //放行
        if (1 == 1) return true;

        //方法拦截：放行OPTIONS
        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            return true;
        }

        //资源拦截：放行静态资源
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/static/")) {
            return true;
        }

        if (requestURI.equals("/error")) {
            return true;
        }

        //资源拦截：检查URI
        Dnt api = system.api(requestURI);
        if (api == null) {
            return true;
        }

        //登录拦截：1=放行
        if ("1".equals(api.getString("check_login"))) {
            return true;
        }

        //登录拦截:检查Token
        String token = request.getHeader("Token");
        //Token不存在
        if (token == null) {
            throw new AblError(401, "Token不存在,请重新登录");
        }
        //Token已失效
        if (!JwtKit.check(token)) {
            throw new AblError(401, "登录超时，请重新登录");
        }

        //TODO 登录拦截:允许登录数量限制
        checkLoginCount(token);

        //权限拦截：1=放行
        if ("1".equals(api.getString("check_permission"))) {
            return true;
        }

        //TODO ：框架完成后，需要放开
        // 权限拦截：检查是否具备访问权限
        // checkApiPermission(requestURI, token);

        return true;
    }

    //检查是否具备访问权限
    private void checkApiPermission(String requestURI, String token) {
        JSONObject tokenParam = JwtKit.getParam(token);
        String userId = tokenParam.getString("userId");
        String userAccount = tokenParam.getString("userAccount");
        JSONArray roleIds = tokenParam.getJSONArray("roleIds");
        List<String> resourceUrls = system.roleApiPath(roleIds);
        if (!resourceUrls.contains(requestURI)) {
            log.info("请求被截拦:{} , 原因:权限不足 ,   访问者信息-> ID:{}, 账号:{}, 角色:{}", requestURI, userId, userAccount, roleIds);
            throw new AblError(401, "权限不足");
        }
    }

    // 允许登录数量限制
    private void checkLoginCount(String token) {
        JSONObject tokenParam = JwtKit.getParam(token);
        String userId = tokenParam.getString("userId");
        String userAccount = tokenParam.getString("userAccount");
        JSONArray roleIds = tokenParam.getJSONArray("roleIds");
        String user_login_max_count = system.dictValue("user_login_max_count", "0");

        //0：无限制
        if (Integer.parseInt(user_login_max_count) == 0) return;

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
        System.out.println(request);
        System.out.println(response);
        System.out.println(object);
        System.out.println();
        System.out.println("888888888888888888888888888888888888888888888888");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) {
        System.out.println(request);
        System.out.println(response);
        System.out.println(object);
        System.out.println();
        System.out.println("7777777777777777777777777777777777777 ");
    }


}
